package com.zwy.ubts.service.impl;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.zwy.ubts.bean.Book;
import com.zwy.ubts.bean.IndentStatus;
import com.zwy.ubts.bean.Order;
import com.zwy.ubts.bean.User;
import com.zwy.ubts.dao.OrderDao;
import com.zwy.ubts.service.*;
import com.zwy.ubts.utils.DateUtil;
import com.zwy.ubts.utils.Mail;
import com.zwy.ubts.utils.MybatisUtils;

import java.util.*;

/**
 * @Author Zhou Wenying
 * @Description:
 * @Date Created in 14:54 2023/3/31
 */
public class OrderServiceImpl extends BaseService<OrderDao> implements OrderService {
    private BookService bookService = new BookServiceImpl();
    private UserService userService = new UserServiceImpl();

    @Override
    public int insertOrder(Integer userId, String addrid, String[] arrayBook) {
        Order order = new Order();
        //保存时间
        order.setOrderCretime(DateUtil.getCurrentDate());
        order.setAddressId(Integer.valueOf(addrid));
        order.setUserId(userId);
        order.setOrderDeal(0);//0 是等待发货，1 部分发货 2全部运送中 3订单完成

        //设置相关信息
        List list = new ArrayList<>();
        Gson gson = new Gson();
        float money = 0f;
        for (int i = 0; i < arrayBook.length; i++) {
            Integer otherUserId = Integer.valueOf(arrayBook[i]);
            Book book = bookService.selectByBookId(otherUserId);
            money += book.getBookMoney();
            Map<String,Object> mapBook = new HashMap<>();
            mapBook.put("book",book);
            mapBook.put("kd_id","");//快递号
            mapBook.put("state",0);
            list.add(mapBook);

            //邮件通知到指定的卖书的人
            User user = userService.selectUserById(book.getUserId());
            Mail.sendMailBookSell(user.getUserEmail(),user.getUserName(),book.getBookName());
            /*将已经购买书籍走book表删除掉*/
            bookService.deleteBookById(otherUserId);
        }
        Map<String,Object> map = new HashMap<>(); /*创建hashmap对象*/
        map.put("info",list);/*添加元素*/
        order.setBookId(gson.toJson(map));/*将一个Map对象转换为JSON格式的字符串，并将其设置为order对象的bookId属性值。*/
        order.setOrderMoney(money);
        System.out.println(order);
        int integer = baseDao.insertOrder(order);

        //更新user的钱
        userService.updateUserMoneyById(userId,-money);

        if (integer != 0){
            commit();
        }
        return integer;
    }

    @Override
    public List<Order> selectOrderByOwnerUserId(Integer userId) {
        List<Order> orders = baseDao.selectOrderByOwnerUserId(userId);
        Gson gson = new Gson();
        for (Order order: orders) {
            System.out.println(order.getBookId());
            JsonObject jsonObject = gson.fromJson(order.getBookId(), JsonObject.class);//将json转为JsonObject
            JsonArray info = jsonObject.getAsJsonArray("info");
            List list = new ArrayList();
            for (int i = 0; i < info.size(); i++) {
                JsonObject item = info.get(i).getAsJsonObject();
                JsonObject bookObj = item.getAsJsonObject("book");
                Book book = gson.fromJson(bookObj.toString(), Book.class);

                IndentStatus indentStatus = new IndentStatus(item.get("kd_id").getAsString(),item.get("state").getAsInt());
                book.setStatus(indentStatus);
                list.add(book);
            }
            order.setBooksList(list);
        }
        return orders;
    }

    @Override
    public List<Order> selectOrderByOtherUserId(Integer userId) {
        //查询订单是否存在指定id的书籍信息
        String like = "%\"userId\":"+userId+",\"bookHot\":%";
        List<Order> orders = baseDao.selectOrderByOtherUserId(like);

        Gson gson = new Gson();
        for (Order order: orders) {
            JsonObject jsonObject = gson.fromJson(order.getBookId(), JsonObject.class);//将json转为JsonObject
            JsonArray info = jsonObject.getAsJsonArray("info");
            List list = new ArrayList();
            for (int i = 0; i < info.size(); i++) {
                JsonObject item = info.get(i).getAsJsonObject();
                JsonObject bookObj = item.getAsJsonObject("book");
                Book book = gson.fromJson(bookObj.toString(), Book.class);

                //state 0 未发货 1 发货
                IndentStatus indentStatus = new IndentStatus(item.get("kd_id").getAsString(),item.get("state").getAsInt());
                book.setStatus(indentStatus);
                list.add(book);
            }
            order.setBooksList(list);
        }
        return orders;
    }

    @Override
    //购买者 确认收货
    public Integer updateBookById(Integer userId, Integer orderId,Integer bookId) {
        Order order = baseDao.selectOrderById(orderId);

        //这里处理钱的增加
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(order.getBookId(), JsonObject.class);//将json转为JsonObject
        JsonArray info = jsonObject.getAsJsonArray("info");

        int all = 0;
        for (int i = 0; i < info.size(); i++) {
            JsonObject item = info.get(i).getAsJsonObject();
            JsonObject book = item.getAsJsonObject("book");
            if (book.get("bookId").getAsInt() == bookId){
                item.addProperty("state",2);//确认收货
                int otherUserId = book.get("userId").getAsInt();
                float bookMoney = book.get("bookMoney").getAsFloat();
                userService.updateUserMoneyById(otherUserId,bookMoney);
            }
            if (item.get("state").getAsInt() == 2){
                all ++;
            }
        }
        if (all == info.size()){
            //0 是等待发货，1 部分发货 2全部运送中 3订单完成
            order.setOrderDeal(3);
        }
        order.setBookId(jsonObject.toString());

        return baseDao.updateBookIdById(order);
    }

    @Override
    //卖书 发货
    public Integer updateBookIdById(Integer otherUserId,Integer orderId,Integer bookId,String kdId) {
        Order order = baseDao.selectOrderById(orderId);
        String bookIdInfo = order.getBookId();
        //解析json
        Gson gson = new Gson();
        JsonObject jsonObject = gson.fromJson(bookIdInfo, JsonObject.class);//将json转为JsonObject
        JsonArray info = jsonObject.getAsJsonArray("info");

        int state = 0;
        for (int i = 0; i < info.size(); i++) {
            JsonObject item = info.get(i).getAsJsonObject();
            System.out.println(item);
            JsonObject book = item.getAsJsonObject("book");
            int oldUserId = book.get("userId").getAsInt();
            int oldBookId = book.get("bookId").getAsInt();

            if (oldUserId  == otherUserId && bookId == oldBookId){
                item.addProperty("kd_id",kdId);
                item.addProperty("state",1);

                //处理邮件
                User user = userService.selectUserById(order.getUserId());

                Mail.sendMailBookBuy(user.getUserEmail(),user.getUserName(),
                        book.get("bookName").getAsString(),orderId,kdId);

            }
            int tmpState = item.get("state").getAsInt();
            if (tmpState == 1){
                state ++;
            }
        }
        //0 是等待发货，1 部分发货 2全部运送中 3订单完成
        if ( info.size() == state){
            //所有订单都完成了发货
            order.setOrderDeal(2);

        }else if (state == 0){
            //一个也没有发货
        }else {
            //部分发货
            order.setOrderDeal(1);
        }

        order.setBookId(jsonObject.toString());

        System.out.println("最新订单啦："+order.getBookId());
        Integer integer = baseDao.updateBookIdById(order);
        commit();
        return integer;
    }

    @Override
    public Order selectOrderById(Integer orderId) {
        return baseDao.selectOrderById(orderId);
    }


}
